<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/dxl/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/dxl/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/dxl/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/dxl/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/dxl/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/dxl/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/dxl/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/dxl/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/dxl/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Django,">










<meta name="description" content="一 Django的视图函数view1.1定义：　　　　一个视图函数（类），简称视图，是一个简单的Python 函数（类）， 1.2 作用：　　　　它接受Web请求并且返回Web响应。 1.3那些可以作为响应的内容：12345- 一张网页的HTML内容- 一个重定向，- 一个404错误，- 一个XML文档，- 一张图片  1.4存放目录：　　只要当前项目目录下面，代码写在哪里都可以。 　　约定俗称：">
<meta name="keywords" content="Django">
<meta property="og:type" content="article">
<meta property="og:title" content="视图函数">
<meta property="og:url" content="http://yoursite.com/2019/09/21/【Django】03视图函数 - 副本/index.html">
<meta property="og:site_name" content="我的快乐时光">
<meta property="og:description" content="一 Django的视图函数view1.1定义：　　　　一个视图函数（类），简称视图，是一个简单的Python 函数（类）， 1.2 作用：　　　　它接受Web请求并且返回Web响应。 1.3那些可以作为响应的内容：12345- 一张网页的HTML内容- 一个重定向，- 一个404错误，- 一个XML文档，- 一张图片  1.4存放目录：　　只要当前项目目录下面，代码写在哪里都可以。 　　约定俗称：">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2019/09/21/【Django】03视图函数%20-%20副本/assets/877318-20160725101445044-1768854009.jpg">
<meta property="og:image" content="http://yoursite.com/2019/09/21/【Django】03视图函数%20-%20副本/assets/copycode-1566636796249.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="http://yoursite.com/2019/09/21/【Django】03视图函数%20-%20副本/assets/copycode-1566636796249.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="http://yoursite.com/2019/09/21/【Django】03视图函数%20-%20副本/assets/copycode-1566636796249.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:image" content="https://common.cnblogs.com/images/copycode.gif">
<meta property="og:updated_time" content="2019-09-21T07:26:26.573Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="视图函数">
<meta name="twitter:description" content="一 Django的视图函数view1.1定义：　　　　一个视图函数（类），简称视图，是一个简单的Python 函数（类）， 1.2 作用：　　　　它接受Web请求并且返回Web响应。 1.3那些可以作为响应的内容：12345- 一张网页的HTML内容- 一个重定向，- 一个404错误，- 一个XML文档，- 一张图片  1.4存放目录：　　只要当前项目目录下面，代码写在哪里都可以。 　　约定俗称：">
<meta name="twitter:image" content="http://yoursite.com/2019/09/21/【Django】03视图函数%20-%20副本/assets/877318-20160725101445044-1768854009.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/dxl/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/09/21/【Django】03视图函数 - 副本/">





  <title>视图函数 | 我的快乐时光</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/dxl/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的快乐时光</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/dxl/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/dxl/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/dxl/2019/09/21/【Django】03视图函数 - 副本/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content>
      <meta itemprop="description" content>
      <meta itemprop="image" content="/dxl/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的快乐时光">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">视图函数</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-21T15:24:35+08:00">
                2019-09-21
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/dxl/categories/Django/" itemprop="url" rel="index">
                    <span itemprop="name">Django</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/dxl/2019/09/21/【Django】03视图函数 - 副本/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/dxl/2019/09/21/【Django】03视图函数 - 副本/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="一-Django的视图函数view"><a href="#一-Django的视图函数view" class="headerlink" title="一 Django的视图函数view"></a>一 Django的视图函数view</h2><h3 id="1-1定义："><a href="#1-1定义：" class="headerlink" title="1.1定义："></a>1.1定义：</h3><p>　　　　一个视图函数（类），简称视图，是一个简单的Python 函数（类），</p>
<h3 id="1-2-作用："><a href="#1-2-作用：" class="headerlink" title="1.2 作用："></a>1.2 作用：</h3><p>　　　　它接受Web请求并且返回Web响应。</p>
<h3 id="1-3那些可以作为响应的内容："><a href="#1-3那些可以作为响应的内容：" class="headerlink" title="1.3那些可以作为响应的内容："></a>1.3那些可以作为响应的内容：</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- 一张网页的HTML内容</span><br><span class="line">- 一个重定向，</span><br><span class="line">- 一个<span class="number">404</span>错误，</span><br><span class="line">- 一个XML文档，</span><br><span class="line">- 一张图片</span><br></pre></td></tr></table></figure>

<h3 id="1-4存放目录："><a href="#1-4存放目录：" class="headerlink" title="1.4存放目录："></a>1.4存放目录：</h3><p>　　只要当前项目目录下面，代码写在哪里都可以。</p>
<p>　　约定俗称：视图放置在项目（project）或应用程序（app）目录中的名为<code>views.py</code>的文件中。</p>
<h3 id="1-5一个简单的视图"><a href="#1-5一个简单的视图" class="headerlink" title="1.5一个简单的视图"></a>1.5一个简单的视图</h3><p>　　下面是一个以HTML文档的形式返回当前日期和时间的视图：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">from django.http import HttpResponse</span><br><span class="line">import datetime</span><br><span class="line"></span><br><span class="line">def current_datetime(request):</span><br><span class="line">    now = datetime.datetime.now()</span><br><span class="line">    html = &quot;&lt;html&gt;&lt;body&gt;It is now %s.&lt;/body&gt;&lt;/html&gt;&quot; % now</span><br><span class="line">    return HttpResponse(html)  #  HttpResponse   返回的类型是文本</span><br></pre></td></tr></table></figure>

<p> 　　解释：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- 我们从 django.http模块导入了HttpResponse类，以及Python的datetime库。</span><br><span class="line">- 我们定义了current_datetime函数。它就是视图函数。每个视图函数都使用HttpRequest对象作为第一个参数，并且通常称之为request。</span><br><span class="line">-注意，视图函数的名称并不重要；不需要用一个统一的命名方式来命名，以便让Django识别它。我们将其命名为current_datetime，是因为这个名称能够比较准确地反映出它实现的能。</span><br><span class="line">- 这个视图会返回一个HttpResponse对象，其中包含生成的响应。每个视图函数都负责返回一个HttpResponse（响应）对象。</span><br></pre></td></tr></table></figure>

<h3 id="1-6Django使用请求和响应对象来通过系统传递状态的过程："><a href="#1-6Django使用请求和响应对象来通过系统传递状态的过程：" class="headerlink" title="1.6Django使用请求和响应对象来通过系统传递状态的过程："></a>1.6Django使用请求和响应对象来通过系统传递状态的过程：</h3><p>　　当浏览器向服务端请求一个页面时，Django创建一个HttpRequest对象，该对象包含关于请求的元数据。然后，Django加载相应的视图，将这个HttpRequest对象作为第一个参数传递给视图函数。</p>
<p>　　每个视图负责返回一个HttpResponse对象。</p>
<p><img src="assets/877318-20160725101445044-1768854009.jpg" alt="img"></p>
<h2 id="二-CBV和FBV"><a href="#二-CBV和FBV" class="headerlink" title="二 CBV和FBV"></a>二 CBV和FBV</h2><h3 id="2-1FBV（function-base-views）"><a href="#2-1FBV（function-base-views）" class="headerlink" title="2.1FBV（function base views）"></a>2.1FBV（function base views）</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">def my_view(request):</span><br><span class="line">     if request.method == &apos;GET&apos;:</span><br><span class="line">            return HttpResponse(&apos;OK&apos;）</span><br></pre></td></tr></table></figure>

<h3 id="2-1CBV（class-base-views）"><a href="#2-1CBV（class-base-views）" class="headerlink" title="2.1CBV（class base views）"></a>2.1CBV（class base views）</h3><p>1、优点:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1. 提高了代码的复用性，可以使用面向对象的技术，比如Mixin（多继承）</span><br><span class="line">2. 可以用不同的函数针对不同的HTTP方法处理，而不是通过很多if判断，提高代码可读性</span><br></pre></td></tr></table></figure>

<h3 id="2-3Djangourl的执行过程"><a href="#2-3Djangourl的执行过程" class="headerlink" title="2.3Djangourl的执行过程"></a>2.3Djangourl的执行过程</h3><p>1、使用CTV和FBV处理GET方法的view。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">FBV：</span><br><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> HttpResponse</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">my_view</span><span class="params">(request)</span>:</span></span><br><span class="line">     <span class="keyword">if</span> request.method == <span class="string">'GET'</span>:</span><br><span class="line">            <span class="keyword">return</span> HttpResponse(<span class="string">'OK'</span>)</span><br><span class="line"></span><br><span class="line">------------------------------------------------------------------------------------------------------------</span><br><span class="line">CBV：views.py和urls.py都要做相应的修改</span><br><span class="line">views:</span><br><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> HttpResponse</span><br><span class="line"><span class="keyword">from</span> django.views <span class="keyword">import</span> View</span><br><span class="line">  </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyView</span><span class="params">(View)</span>:</span></span><br><span class="line">      <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self, request)</span>:</span></span><br><span class="line">            <span class="keyword">return</span> HttpResponse(<span class="string">'OK'</span>)</span><br><span class="line">urls:</span><br><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url</span><br><span class="line"><span class="keyword">from</span> myapp.views <span class="keyword">import</span> MyView <span class="comment">#引入我们在views.py里面创建的类</span></span><br><span class="line">  </span><br><span class="line">urlpatterns = [</span><br><span class="line">     url(<span class="string">r'^index/$'</span>, MyView.as_view()), <span class="comment">#'^index/$'与写入的路径有关</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>2、cbv执行流程</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">　　　Django的url是将一个请求分配给可调用的函数的，而不是一个<span class="class"><span class="keyword">class</span>。针对这个问题，<span class="title">class</span>-<span class="title">based</span> <span class="title">view</span>提供了一个<span class="title">as_view</span><span class="params">()</span>静态方法（也就是类方法），调用这个方法，会创建一个类的实例，然后通过实例调用<span class="title">dispatch</span><span class="params">()</span>方法，<span class="title">dispatch</span><span class="params">()</span>方法会根据<span class="title">request</span>的<span class="title">method</span>的不同调用相应的方法来处理<span class="title">request</span>（如<span class="title">get</span><span class="params">()</span>，``<span class="title">post</span><span class="params">()</span>等）。到这里，这些方法和<span class="title">function</span>-<span class="title">based</span> <span class="title">view</span>差不多了，要接收<span class="title">request</span>，得到一个<span class="title">response</span>返回。如果方法没有定义，会抛出<span class="title">HttpResponseNotAllowed</span>异常</span></span><br></pre></td></tr></table></figure>

<p>　　　　CBV传参，和FBV类似，有名分组，无名分组</p>
<p>　　　　url写法：无名分组的</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"> url(<span class="string">r'^cv/(\d&#123;2&#125;)/'</span>, views.Myd.as_view(),name=<span class="string">'cv'</span>),</span><br><span class="line"> url(<span class="string">r'^cv/(?P&lt;n&gt;\d&#123;2&#125;)/'</span>, views.Myd.as_view(name=<span class="string">'xxx'</span>),name=<span class="string">'cv'</span>),</span><br><span class="line"><span class="comment">#如果想给类的name属性赋值，前提你的Myd类里面必须有name属性（类属性，定义init方法来接受属性行不通，但是可以自行研究一下，看看如何行通，意义不大），并且之前类里面的name属性的值会被覆盖掉</span></span><br></pre></td></tr></table></figure>

<p>3、类写法：</p>
<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="assets/copycode-1566636796249.gif" alt="复制代码"></a></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">class Myd(View):</span><br><span class="line">    name = &apos;sb&apos;</span><br><span class="line"></span><br><span class="line">    def get(self,request,n):</span><br><span class="line">        print(&apos;get方法执行了&apos;)</span><br><span class="line">        print(&apos;&gt;&gt;&gt;&apos;,n)</span><br><span class="line">        return render(request,&apos;cvpost.html&apos;,&#123;&apos;name&apos;:self.name&#125;)</span><br><span class="line"></span><br><span class="line">    def post(self,request,n):</span><br><span class="line">        print(&apos;post方法被执行了&apos;)</span><br><span class="line">        return HttpResponse(&apos;post&apos;)</span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<p>4、添加类的属性的方法</p>
<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="assets/copycode-1566636796249.gif" alt="复制代码"></a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#first</span></span><br><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> HttpResponse</span><br><span class="line"><span class="keyword">from</span> django.views <span class="keyword">import</span> View</span><br><span class="line">  </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GreetingView</span><span class="params">(View)</span>:</span></span><br><span class="line">    name = <span class="string">"yuan"</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self, request)</span>:</span></span><br><span class="line">         <span class="keyword">return</span> HttpResponse(self.name)</span><br><span class="line">  </span><br><span class="line"><span class="comment"># You can override that in a subclass</span></span><br><span class="line">  </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MorningGreetingView</span><span class="params">(GreetingView)</span>:</span></span><br><span class="line">    name= <span class="string">"alex"</span></span><br><span class="line"><span class="comment">#父类可以被子类</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#second</span></span><br><span class="line">urlpatterns = [</span><br><span class="line">   url(<span class="string">r'^index/$'</span>, GreetingView.as_view(name=<span class="string">"egon"</span>)), <span class="comment">#类里面必须有name属性，并且会被传进来的这个属性值给覆盖掉</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<h2 id="三-使用Mixin"><a href="#三-使用Mixin" class="headerlink" title="三 使用Mixin"></a>三 使用Mixin</h2><p>　　cbv的实现原理通过看django的源码就很容易明白，大体就是由url路由到这个cbv之后，通过cbv内部的dispatch方法进行分发，将get请求分发给cbv.get方法处理，将post请求分发给cbv.post方法处理，其他方法类似。怎么利用多态呢？cbv里引入了mixin的概念。Mixin就是写好了的一些基础类，然后通过不同的Mixin组合成为最终想要的类。</p>
<p>　　所以，理解cbv的基础是，理解Mixin。Django中使用Mixin来重用代码，一个View Class可以继承多个Mixin，但是只能继承一个View（包括View的子类），推荐把View写在最右边，多个Mixin写在左边。</p>
<h2 id="四-给视图加装饰器"><a href="#四-给视图加装饰器" class="headerlink" title="四 给视图加装饰器"></a>四 给视图加装饰器</h2><h3 id="4-1使用装饰器装饰FBV"><a href="#4-1使用装饰器装饰FBV" class="headerlink" title="4.1使用装饰器装饰FBV"></a>4.1使用装饰器装饰FBV</h3><p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">wrapper</span><span class="params">(func)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">inner</span><span class="params">(*args, **kwargs)</span>:</span></span><br><span class="line">        start_time = time.time()</span><br><span class="line">        ret = func(*args, **kwargs)</span><br><span class="line">        end_time = time.time()</span><br><span class="line">        print(<span class="string">"used:"</span>, end_time-start_time)</span><br><span class="line">        <span class="keyword">return</span> ret</span><br><span class="line">    <span class="keyword">return</span> inner</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># FBV版添加班级</span></span><br><span class="line"><span class="meta">@wrapper</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_class</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">"POST"</span>:</span><br><span class="line">        class_name = request.POST.get(<span class="string">"class_name"</span>)</span><br><span class="line">        models.Classes.objects.create(name=class_name)</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">"/class_list/"</span>)</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">"add_class.html"</span>)</span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<h3 id="4-2使用装饰器装饰CBV"><a href="#4-2使用装饰器装饰CBV" class="headerlink" title="4.2使用装饰器装饰CBV"></a>4.2使用装饰器装饰CBV</h3><p>　　　类中的方法与独立函数不完全相同，因此不能直接将函数装饰器应用于类中的方法 ，我们需要先将其转换为方法装饰器。</p>
<p>　　Django中提供了method_decorator装饰器用于将函数装饰器转换为方法装饰器。</p>
<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.views <span class="keyword">import</span> View</span><br><span class="line"><span class="keyword">from</span> django.utils.decorators <span class="keyword">import</span> method_decorator</span><br><span class="line"><span class="comment">#first：给单独的方法加装饰器</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AddClass</span><span class="params">(View)</span>:</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @method_decorator(wrapper)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> render(request, <span class="string">"add_class.html"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        class_name = request.POST.get(<span class="string">"class_name"</span>)</span><br><span class="line">        models.Classes.objects.create(name=class_name)</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">"/class_list/"</span>)</span><br><span class="line"><span class="comment">#second:给类中的所有方法加装饰器</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Login</span><span class="params">(View)</span>:</span></span><br><span class="line"><span class="meta">    @method_decorator(login_test)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">dispatch</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        print(<span class="string">'before'</span>)</span><br><span class="line">        obj = super(Login,self).dispatch(request, *args, **kwargs)</span><br><span class="line">        print(<span class="string">'after'</span>)</span><br><span class="line">        <span class="keyword">return</span> obj</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> render(request,<span class="string">'login.html'</span>)</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        print(request.POST.get(<span class="string">'user'</span>))</span><br><span class="line">        <span class="keyword">return</span> HttpResponse(<span class="string">'Login.post'</span>)</span><br><span class="line"><span class="comment">#third:直接添加在类上，后面的name表示只给get添加装饰器</span></span><br><span class="line"><span class="meta">@method_decorator(login_test, name='get')  #get是给get方法加</span></span><br><span class="line"><span class="meta">@method_decorator(login_test, name='post')  #post是给post方法加</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">IndexView</span><span class="params">(View)</span>:</span></span><br><span class="line">　　　　<span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request)</span>：</span></span><br><span class="line"><span class="function">　　　　　　<span class="title">pass</span></span></span><br><span class="line"><span class="function">#总结：</span></span><br><span class="line"><span class="function">#1、给类添加是必须声明<span class="title">name</span></span></span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<h3 id="4-3csrf-token的装饰器"><a href="#4-3csrf-token的装饰器" class="headerlink" title="4.3csrf_token的装饰器"></a>4.3csrf_token的装饰器</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.views.decorators.csrf <span class="keyword">import</span> csrf_exempt,csrf_protect</span><br><span class="line"><span class="meta">@csrf_protect，#为当前函数强制设置防跨站请求伪造功能，即便settings中没有设置csrfToken全局中间件。</span></span><br><span class="line"><span class="meta">@csrf_exempt，# 取消当前函数防跨站请求伪造功能，即便settings中设置了全局中间件。</span></span><br></pre></td></tr></table></figure>

<h3 id="4-4重写dispatch方法"><a href="#4-4重写dispatch方法" class="headerlink" title="4.4重写dispatch方法"></a>4.4重写dispatch方法</h3><p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 使用CBV时要注意，请求过来后会先执行dispatch()这个方法，如果需要批量对具体的请求处理方法，如get，post等做一些操作的时候，这里我们可以手动改写dispatch方法，这个dispatch方法就和在FBV上加装饰器的效果一样。</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Login</span><span class="params">(View)</span>:</span></span><br><span class="line">     </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">dispatch</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        print(<span class="string">'before'</span>)</span><br><span class="line">        obj = super(Login,self).dispatch(request, *args, **kwargs)</span><br><span class="line">        print(<span class="string">'after'</span>)</span><br><span class="line">        <span class="keyword">return</span> obj</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> render(request,<span class="string">'login.html'</span>)</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        print(request.POST.get(<span class="string">'user'</span>))</span><br><span class="line">        <span class="keyword">return</span> HttpResponse(<span class="string">'Login.post'</span>)</span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<h2 id="五-request对象"><a href="#五-request对象" class="headerlink" title="五 request对象"></a>五 request对象</h2><p>　　当一个页面被请求时，Django就会创建一个包含本次请求原信息的HttpRequest对象。<br>　　Django会将这个对象自动传递给响应的视图函数，一般视图函数约定俗成地使用 request 参数承接这个对象。</p>
<p>　　<a href="https://docs.djangoproject.com/en/1.11/ref/request-response/" target="_blank" rel="noopener">官方文档</a></p>
<h3 id="5-1请求相关的常用值"><a href="#5-1请求相关的常用值" class="headerlink" title="5.1请求相关的常用值"></a>5.1请求相关的常用值</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- path_info     返回用户访问url，不包括域名</span><br><span class="line">- method        请求中使用的HTTP方法的字符串表示，全大写表示。</span><br><span class="line">- GET           包含所有HTTP  GET参数的类字典对象</span><br><span class="line">- POST          包含所有HTTP POST参数的类字典对象</span><br><span class="line">- body          请求体，byte类型 request.POST的数据就是从body里面提取到的</span><br></pre></td></tr></table></figure>

<h3 id="5-2属性"><a href="#5-2属性" class="headerlink" title="5.2属性"></a>5.2属性</h3><p>1、相关属性</p>
<p>　　所有的属性应该被认为是只读的，除非另有说明。</p>
<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="assets/copycode-1566636796249.gif" alt="复制代码"></a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br></pre></td><td class="code"><pre><span class="line">属性：</span><br><span class="line">　　django将请求报文中的请求行、头部信息、内容主体封装成 HttpRequest 类中的属性。</span><br><span class="line">   除了特殊说明的之外，其他均为只读的。</span><br><span class="line"></span><br><span class="line"><span class="number">0.</span>HttpRequest.scheme</span><br><span class="line">   表示请求方案的字符串（通常为http或https）</span><br><span class="line"></span><br><span class="line"><span class="number">1.</span>HttpRequest.body</span><br><span class="line">　　一个字符串，代表请求报文的主体。在处理非 HTTP 形式的报文时非常有用，例如：二进制图片、XML,Json等。</span><br><span class="line">　　但是，如果要处理表单数据的时候，推荐还是使用 HttpRequest.POST 。</span><br><span class="line">　　另外，我们还可以用 python 的类文件方法去操作它，详情参考 HttpRequest.read() 。</span><br><span class="line"></span><br><span class="line"><span class="number">2.</span>HttpRequest.path</span><br><span class="line">　　一个字符串，表示请求的路径组件（不含域名）。</span><br><span class="line">　　例如：<span class="string">"/music/bands/the_beatles/"</span></span><br><span class="line">　　</span><br><span class="line"><span class="number">3.</span>HttpRequest.method</span><br><span class="line"></span><br><span class="line">　　一个字符串，表示请求使用的HTTP 方法。必须使用大写。</span><br><span class="line">　　例如：<span class="string">"GET"</span>、<span class="string">"POST"</span></span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line"><span class="number">4.</span>HttpRequest.encoding</span><br><span class="line"></span><br><span class="line">　　一个字符串，表示提交的数据的编码方式（如果为 <span class="literal">None</span> 则表示使用 DEFAULT_CHARSET 的设置，默认为 <span class="string">'utf-8'</span>）。</span><br><span class="line">   这个属性是可写的，你可以修改它来修改访问表单数据使用的编码。</span><br><span class="line">   接下来对属性的任何访问（例如从 GET 或 POST 中读取数据）将使用新的 encoding 值。</span><br><span class="line">   如果你知道表单数据的编码不是 DEFAULT_CHARSET ，则使用它。</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line"><span class="number">5.</span>HttpRequest.GET </span><br><span class="line">　　一个类似于字典的对象，包含 HTTP GET 的所有参数。详情请参考 QueryDict 对象。</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line"><span class="number">6.</span>HttpRequest.POST</span><br><span class="line">　　一个类似于字典的对象，如果请求中包含表单数据，则将这些数据封装成 QueryDict 对象。</span><br><span class="line">　　POST 请求可以带有空的 POST 字典 —— 如果通过 HTTP POST 方法发送一个表单，但是表单中没有任何的数据，QueryDict 对象依然会被创建。</span><br><span class="line">   因此，不应该使用 <span class="keyword">if</span> request.POST  来检查使用的是否是POST 方法；应该使用 <span class="keyword">if</span> request.method == <span class="string">"POST"</span> </span><br><span class="line">　　另外：如果使用 POST 上传文件的话，文件信息将包含在 FILES 属性中。</span><br><span class="line"></span><br><span class="line"> <span class="number">7.</span>HttpRequest.COOKIES</span><br><span class="line">　　一个标准的Python 字典，包含所有的cookie。键和值都为字符串。</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line"><span class="number">8.</span>HttpRequest.FILES</span><br><span class="line"></span><br><span class="line">　　一个类似于字典的对象，包含所有的上传文件信息。</span><br><span class="line">   FILES 中的每个键为&lt;input type=<span class="string">"file"</span> name=<span class="string">""</span> /&gt; 中的name，值则为对应的数据。</span><br><span class="line">　　注意，FILES 只有在请求的方法为POST 且提交的&lt;form&gt; 带有enctype=<span class="string">"multipart/form-data"</span> 的情况下才会</span><br><span class="line">   包含数据。否则，FILES 将为一个空的类似于字典的对象。</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line"><span class="number">9.</span>HttpRequest.META</span><br><span class="line"> 　　一个标准的Python 字典，包含所有的HTTP 首部（请求头信息）。具体的头部信息取决于客户端和服务器，下面是一些示例：</span><br><span class="line"></span><br><span class="line">    CONTENT_LENGTH —— 请求的正文的长度（是一个字符串）。</span><br><span class="line">    CONTENT_TYPE —— 请求的正文的MIME 类型。</span><br><span class="line">    HTTP_ACCEPT —— 响应可接收的Content-Type。</span><br><span class="line">    HTTP_ACCEPT_ENCODING —— 响应可接收的编码。</span><br><span class="line">    HTTP_ACCEPT_LANGUAGE —— 响应可接收的语言。</span><br><span class="line">    HTTP_HOST —— 客服端发送的HTTP Host 头部。</span><br><span class="line">    HTTP_REFERER —— Referring 页面。</span><br><span class="line">    HTTP_USER_AGENT —— 客户端的user-agent 字符串。</span><br><span class="line">    QUERY_STRING —— 单个字符串形式的查询字符串（未解析过的形式）。</span><br><span class="line">    REMOTE_ADDR —— 客户端的IP 地址。</span><br><span class="line">    REMOTE_HOST —— 客户端的主机名。</span><br><span class="line">    REMOTE_USER —— 服务器认证后的用户。</span><br><span class="line">    REQUEST_METHOD —— 一个字符串，例如<span class="string">"GET"</span> 或<span class="string">"POST"</span>。</span><br><span class="line">    SERVER_NAME —— 服务器的主机名。</span><br><span class="line">    SERVER_PORT —— 服务器的端口（是一个字符串）。</span><br><span class="line"> 　　从上面可以看到，除 CONTENT_LENGTH 和 CONTENT_TYPE 之外，请求中的任何 HTTP 首部转换为 META 的键时，</span><br><span class="line">    都会将所有字母大写并将连接符替换为下划线最后加上 HTTP_  前缀。</span><br><span class="line">    所以，一个叫做 X-Bender 的头部将转换成 META 中的 HTTP_X_BENDER 键。</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"><span class="number">10.</span>HttpRequest.user</span><br><span class="line">　　一个 AUTH_USER_MODEL 类型的对象，表示当前登录的用户。</span><br><span class="line">　　如果用户当前没有登录，user 将设置为 django.contrib.auth.models.AnonymousUser 的一个实例。你可以通过 is_authenticated() 区分它们。</span><br><span class="line"></span><br><span class="line">    例如：</span><br><span class="line">    <span class="keyword">if</span> request.user.is_authenticated():</span><br><span class="line">        <span class="comment"># Do something for logged-in users.</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="comment"># Do something for anonymous users.</span></span><br><span class="line">     </span><br><span class="line"></span><br><span class="line">     　　user 只有当Django 启用 AuthenticationMiddleware 中间件时才可用。</span><br><span class="line"></span><br><span class="line">     -------------------------------------------------------------------------------------</span><br><span class="line"></span><br><span class="line">    匿名用户</span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">models</span>.<span class="title">AnonymousUser</span></span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class">    <span class="title">django</span>.<span class="title">contrib</span>.<span class="title">auth</span>.<span class="title">models</span>.<span class="title">AnonymousUser</span> 类实现了<span class="title">django</span>.<span class="title">contrib</span>.<span class="title">auth</span>.<span class="title">models</span>.<span class="title">User</span> 接口，但具有下面几个不同点：</span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class">    <span class="title">id</span> 永远为<span class="title">None</span>。</span></span><br><span class="line"><span class="class">    <span class="title">username</span> 永远为空字符串。</span></span><br><span class="line"><span class="class">    <span class="title">get_username</span><span class="params">()</span> 永远返回空字符串。</span></span><br><span class="line"><span class="class">    <span class="title">is_staff</span> 和 <span class="title">is_superuser</span> 永远为<span class="title">False</span>。</span></span><br><span class="line"><span class="class">    <span class="title">is_active</span> 永远为 <span class="title">False</span>。</span></span><br><span class="line"><span class="class">    <span class="title">groups</span> 和 <span class="title">user_permissions</span> 永远为空。</span></span><br><span class="line"><span class="class">    <span class="title">is_anonymous</span><span class="params">()</span> 返回<span class="title">True</span> 而不是<span class="title">False</span>。</span></span><br><span class="line"><span class="class">    <span class="title">is_authenticated</span><span class="params">()</span> 返回<span class="title">False</span> 而不是<span class="title">True</span>。</span></span><br><span class="line"><span class="class">    <span class="title">set_password</span><span class="params">()</span>、<span class="title">check_password</span><span class="params">()</span>、<span class="title">save</span><span class="params">()</span> 和<span class="title">delete</span><span class="params">()</span> 引发 <span class="title">NotImplementedError</span>。</span></span><br><span class="line"><span class="class">    <span class="title">New</span> <span class="title">in</span> <span class="title">Django</span> 1.8:</span></span><br><span class="line">    新增 AnonymousUser.get_username() 以更好地模拟 django.contrib.auth.models.User。</span><br><span class="line"></span><br><span class="line"><span class="number">11.</span>HttpRequest.session</span><br><span class="line"></span><br><span class="line"> 　　一个既可读又可写的类似于字典的对象，表示当前的会话。只有当Django 启用会话的支持时才可用。</span><br><span class="line">    完整的细节参见会话的文档。</span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<p> 2、文件上传示例</p>
<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">def upload(request):</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    保存上传文件前，数据需要存放在某个位置。默认当上传文件小于2.5M时，django会将上传文件的全部内容读进内存。从内存读取一次，写磁盘一次。</span><br><span class="line">    但当上传文件很大时，django会把上传文件写到临时文件中，然后存放到系统临时文件夹中。</span><br><span class="line">    :param request: </span><br><span class="line">    :return: </span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    if request.method == &quot;POST&quot;:</span><br><span class="line">        # 从请求的FILES中获取上传文件的文件名，file为页面上type=files类型input的name属性值</span><br><span class="line">        filename = request.FILES[&quot;file&quot;].name</span><br><span class="line">        # 在项目目录下新建一个文件</span><br><span class="line">        with open(filename, &quot;wb&quot;) as f:</span><br><span class="line">            # 从上传的文件对象中一点一点读</span><br><span class="line">            for chunk in request.FILES[&quot;file&quot;].chunks():</span><br><span class="line">                # 写入本地文件</span><br><span class="line">                f.write(chunk)</span><br><span class="line">        return HttpResponse(&quot;上传OK&quot;)</span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<h3 id="5-3-方法"><a href="#5-3-方法" class="headerlink" title="5.3 方法"></a>5.3 方法</h3><p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>HttpRequest.get_host()</span><br><span class="line"></span><br><span class="line">　　根据从HTTP_X_FORWARDED_HOST（如果打开 USE_X_FORWARDED_HOST，默认为<span class="literal">False</span>）和 HTTP_HOST 头部信息返回请求的原始主机。</span><br><span class="line">   如果这两个头部没有提供相应的值，则使用SERVER_NAME 和SERVER_PORT，在PEP <span class="number">3333</span> 中有详细描述。</span><br><span class="line"></span><br><span class="line">　　USE_X_FORWARDED_HOST：一个布尔值，用于指定是否优先使用 X-Forwarded-Host 首部，仅在代理设置了该首部的情况下，才可以被使用。</span><br><span class="line"></span><br><span class="line">　　例如：<span class="string">"127.0.0.1:8000"</span></span><br><span class="line"></span><br><span class="line">　　注意：当主机位于多个代理后面时，get_host() 方法将会失败。除非使用中间件重写代理的首部。</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"><span class="number">2.</span>HttpRequest.get_full_path()</span><br><span class="line"></span><br><span class="line">　　返回 path，如果可以将加上查询字符串。</span><br><span class="line"></span><br><span class="line">　　例如：<span class="string">"/music/bands/the_beatles/?print=true"</span></span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line"><span class="number">3.</span>HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt=<span class="string">''</span>, max_age=<span class="literal">None</span>)</span><br><span class="line"></span><br><span class="line">　　返回签名过的Cookie 对应的值，如果签名不再合法则返回django.core.signing.BadSignature。</span><br><span class="line"></span><br><span class="line">　　如果提供 default 参数，将不会引发异常并返回 default 的值。</span><br><span class="line"></span><br><span class="line">　　可选参数salt 可以用来对安全密钥强力攻击提供额外的保护。max_age 参数用于检查Cookie 对应的时间戳以确保Cookie 的时间不会超过max_age 秒。</span><br><span class="line"></span><br><span class="line">        复制代码</span><br><span class="line">        &gt;&gt;&gt; request.get_signed_cookie(<span class="string">'name'</span>)</span><br><span class="line">        <span class="string">'Tony'</span></span><br><span class="line">        &gt;&gt;&gt; request.get_signed_cookie(<span class="string">'name'</span>, salt=<span class="string">'name-salt'</span>)</span><br><span class="line">        <span class="string">'Tony'</span> <span class="comment"># 假设在设置cookie的时候使用的是相同的salt</span></span><br><span class="line">        &gt;&gt;&gt; request.get_signed_cookie(<span class="string">'non-existing-cookie'</span>)</span><br><span class="line">        ...</span><br><span class="line">        KeyError: <span class="string">'non-existing-cookie'</span>    <span class="comment"># 没有相应的键时触发异常</span></span><br><span class="line">        &gt;&gt;&gt; request.get_signed_cookie(<span class="string">'non-existing-cookie'</span>, <span class="literal">False</span>)</span><br><span class="line">        <span class="literal">False</span></span><br><span class="line">        &gt;&gt;&gt; request.get_signed_cookie(<span class="string">'cookie-that-was-tampered-with'</span>)</span><br><span class="line">        ...</span><br><span class="line">        BadSignature: ...    </span><br><span class="line">        &gt;&gt;&gt; request.get_signed_cookie(<span class="string">'name'</span>, max_age=<span class="number">60</span>)</span><br><span class="line">        ...</span><br><span class="line">        SignatureExpired: Signature age <span class="number">1677.3839159</span> &gt; <span class="number">60</span> seconds</span><br><span class="line">        &gt;&gt;&gt; request.get_signed_cookie(<span class="string">'name'</span>, <span class="literal">False</span>, max_age=<span class="number">60</span>)</span><br><span class="line">        <span class="literal">False</span></span><br><span class="line">        复制代码</span><br><span class="line">         </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="number">4.</span>HttpRequest.is_secure()</span><br><span class="line">　　如果请求时是安全的，则返回<span class="literal">True</span>；即请求通是过 HTTPS 发起的。</span><br><span class="line"></span><br><span class="line"><span class="number">5.</span>HttpRequest.is_ajax()</span><br><span class="line"></span><br><span class="line">　　如果请求是通过XMLHttpRequest 发起的，则返回<span class="literal">True</span>，方法是检查 HTTP_X_REQUESTED_WITH 相应的首部是否是字符串<span class="string">'XMLHttpRequest'</span>。</span><br><span class="line"></span><br><span class="line">　　大部分现代的 JavaScript 库都会发送这个头部。如果你编写自己的 XMLHttpRequest 调用（在浏览器端），你必须手工设置这个值来让 is_ajax() 可以工作。</span><br><span class="line"></span><br><span class="line">　　如果一个响应需要根据请求是否是通过AJAX 发起的，并且你正在使用某种形式的缓存例如Django 的 cache middleware， </span><br><span class="line">   你应该使用 vary_on_headers(<span class="string">'HTTP_X_REQUESTED_WITH'</span>) 装饰你的视图以让响应能够正确地缓存。</span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<p>eg:　</p>
<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render,HttpResponse,redirect</span><br><span class="line"></span><br><span class="line"><span class="comment"># Create your views here.</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request)</span>:</span></span><br><span class="line">    print(request.method) <span class="comment">#请求方式</span></span><br><span class="line">    print(request.path)   <span class="comment">#请求路径，不带参数的</span></span><br><span class="line">    print(request.POST)   <span class="comment">#post请求数据  字典格式</span></span><br><span class="line">    print(request.GET)    <span class="comment">#get的请求数据  字典格式</span></span><br><span class="line">    print(request.META)   <span class="comment">#请求头信息,将来用到哪个咱们再说哪个</span></span><br><span class="line">    print(request.get_full_path())   <span class="comment">#获取请求路径带参数的，/index/?a=1</span></span><br><span class="line">    print(request.is_ajax())   <span class="comment">#判断是不是ajax发送的请求，True和False</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">        Django一定最后会响应一个HttpResponse的示例对象</span></span><br><span class="line"><span class="string">        三种形式：</span></span><br><span class="line"><span class="string">            1 HttpResponse('字符串') 最简单</span></span><br><span class="line"><span class="string">            2 render(页面)   最重要</span></span><br><span class="line"><span class="string">                2.1 两个功能</span></span><br><span class="line"><span class="string">                    -- 读取文件字符串</span></span><br><span class="line"><span class="string">                    -- 嵌入变量(模板渲染) html里面：&#123;&#123; name &#125;&#125; ， &#123;'name':'chao'&#125;作为render的第三个参数，想写多个变量&#123;'name':'chao','hobby':['篮球','羽毛球']....&#125;</span></span><br><span class="line"><span class="string">            3 redirect() 重定向  某个网站搬家了，网址变了，访问原来的网址就重定向到一个新网址，就叫做重定向，网站自己做的重定向，你访问还是访问的你之前的，你自己啥也不用做，浏览器发送请求，然后服务端响应，然后服务端告诉浏览器，你直接跳转到另外一个网址上，那么浏览器又自动发送了另外一个请求，发送到服务端，服务端返回一个页面，包含两次请求，登陆成功后跳转到网站的首页，网站首页的网址和你login登陆页面的网址是不用的。</span></span><br><span class="line"><span class="string">                </span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> render(request,<span class="string">'index.html'</span>,&#123;<span class="string">'name'</span>:<span class="string">'chao'</span>&#125;)</span><br><span class="line">    <span class="comment"># return HttpResponse('ok')</span></span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);" target="_blank" rel="noopener"><img src="https://common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></p>
<p>　　注意：键值对的值是多个的时候,比如checkbox类型的input标签，select标签，需要用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">request.POST.getlist(&quot;hobby&quot;)</span><br></pre></td></tr></table></figure>

<h2 id="六-response对象"><a href="#六-response对象" class="headerlink" title="六 response对象"></a>六 response对象</h2><p>　　与由Django自动创建的HttpRequest对象相比，HttpResponse对象是我们的职责范围了。我们写的每个视图都需要实例化，填充和返回一个HttpResponse。</p>
<h3 id="6-1HttpResponse"><a href="#6-1HttpResponse" class="headerlink" title="6.1HttpResponse"></a>6.1HttpResponse</h3><p>1、传递字符串</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">from django.http import HttpResponse</span><br><span class="line">response = HttpResponse(&quot;Here&apos;s the text of the Web page.&quot;)</span><br><span class="line">response = HttpResponse(&quot;Text only, please.&quot;, content_type=&quot;text/plain&quot;)</span><br></pre></td></tr></table></figure>

<p>2、设置或删除响应头信息</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">response = HttpResponse()</span><br><span class="line">response[&apos;Content-Type&apos;] = &apos;text/html; charset=UTF-8&apos;</span><br><span class="line">del response[&apos;Content-Type&apos;]</span><br></pre></td></tr></table></figure>

<p>3、属性</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">HttpResponse.content：响应内容</span><br><span class="line">HttpResponse.charset：响应内容的编码</span><br><span class="line">HttpResponse.status_code：响应的状态码</span><br></pre></td></tr></table></figure>

<h3 id="6-2JsonResponse对象"><a href="#6-2JsonResponse对象" class="headerlink" title="6.2JsonResponse对象"></a>6.2JsonResponse对象</h3><p>1、定义</p>
<p>　 JsonResponse是HttpResponse的子类，专门用来生成JSON编码的响应。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> JsonResponse</span><br><span class="line"></span><br><span class="line">response = JsonResponse(&#123;<span class="string">'foo'</span>: <span class="string">'bar'</span>&#125;)</span><br><span class="line">print(response.content)</span><br><span class="line"><span class="string">b'&#123;"foo": "bar"&#125;'</span></span><br></pre></td></tr></table></figure>

<p>2、参数解释</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">JsonResponse</span><span class="params">(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None,**kwargs)</span></span></span><br><span class="line"><span class="class">　　　　这个类是<span class="title">HttpRespon</span>的子类，它主要和父类的区别在于：</span></span><br><span class="line"><span class="class">　　　　1.它的默认<span class="title">Content</span>-<span class="title">Type</span> 被设置为： <span class="title">application</span>/<span class="title">json</span></span></span><br><span class="line">　　　　2.第一个参数，data应该是一个字典类型，当 safe 这个参数被设置为：False ,那data可以填入任何能被转换为JSON格式的对象，比如list, tuple, set。 默认的safe 参数是 True. 如果你传入的data数据类型不是字典类型，那么它就会抛出 TypeError的异常。</span><br><span class="line">　　　　<span class="number">3.j</span>son_dumps_params参数是一个字典,它将调用json.dumps()方法并将字典中的参数传入给该方法。</span><br></pre></td></tr></table></figure>

<p>3、使用HttpResponse返回json字符串</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#如果这样返回，ajax还需要进行json解析</span></span><br><span class="line"><span class="comment">#views.py</span></span><br><span class="line"><span class="keyword">return</span> HttpResponse(json.dumps(&#123;<span class="string">"msg"</span>:<span class="string">"ok!"</span>&#125;))</span><br><span class="line"></span><br><span class="line"><span class="comment">#index.html</span></span><br><span class="line">var data=json.parse(data)</span><br><span class="line">console.log(data.msg);</span><br></pre></td></tr></table></figure>

<p>4、指定content_type类型为json返回HttpResponse对象来</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">return HttpResponse(json.dumps(data),content_type=&quot;application/json&quot;)</span><br></pre></td></tr></table></figure>

<p>5、使用JsonResponse返回JsonResponse对象</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#如果这样返回，两边都不需要进行json的序列化与反序列化，ajax接受的直接是一个对象</span></span><br><span class="line"><span class="comment">#views.py</span></span><br><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> JsonResponse</span><br><span class="line"><span class="keyword">return</span> JsonResponse(&#123;<span class="string">"msg"</span>:<span class="string">"ok!"</span>&#125;)</span><br><span class="line"><span class="comment">#index.html</span></span><br><span class="line">console.log(data.msg);</span><br></pre></td></tr></table></figure>

<p> 6、JsonResponse返回非字典类型的json字符串</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">response = JsonResponse([1, 2, 3], safe=False)</span><br></pre></td></tr></table></figure>

<h3 id="6-3render"><a href="#6-3render" class="headerlink" title="6.3render"></a>6.3render</h3><p>1、初始</p>
<p>　　　结合一个给定的模板和一个给定的上下文字典，并返回一个渲染后的 HttpResponse 对象。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">　　　　　　参数：</span><br><span class="line">　　　　　　　　request： 用于生成响应的请求对象。</span><br><span class="line">　　　　　　　　template_name：要使用的模板的完整名称，可选的参数</span><br><span class="line">　　　　　　　　context：添加到模板上下文的一个字典。默认是一个空字典。如果字典中的某个值是可调用的，视图将在渲染模板之前调用它。</span><br><span class="line">　　　　　　　　content_type：生成的文档要使用的MIME类型。默认为 DEFAULT_CONTENT_TYPE 设置的值。默认为<span class="string">'text/html'</span></span><br><span class="line">　　　　　　　　status：响应的状态码。默认为<span class="number">200</span>。</span><br><span class="line">　　　　　　　　useing: 用于加载模板的模板引擎的名称。</span><br><span class="line"></span><br><span class="line">　　　　　　一个简单的例子：</span><br><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">my_view</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="comment"># 视图的代码写在这里</span></span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">'myapp/index.html'</span>, &#123;<span class="string">'foo'</span>: <span class="string">'bar'</span>&#125;)</span><br></pre></td></tr></table></figure>

<p> 2、render与HttpResponse的关系</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">from django.http import HttpResponse</span><br><span class="line">from django.template import loader</span><br><span class="line"></span><br><span class="line">def my_view(request):</span><br><span class="line">    # 视图代码写在这里</span><br><span class="line">    t = loader.get_template(&apos;myapp/index.html&apos;)</span><br><span class="line">    c = &#123;&apos;foo&apos;: &apos;bar&apos;&#125;</span><br><span class="line">    return HttpResponse(t.render(c, request))</span><br></pre></td></tr></table></figure>

<h3 id="6-4redirect"><a href="#6-4redirect" class="headerlink" title="6.4redirect"></a>6.4redirect</h3><p>1、参数解释</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">参数可以是：</span><br><span class="line"></span><br><span class="line">    <span class="number">1.</span> 一个模型：将调用模型的get_absolute_url() 函数</span><br><span class="line">    <span class="number">2.</span>一个视图，可以带有参数：将使用urlresolvers.reverse 来反向解析名称</span><br><span class="line">    <span class="number">3.</span>一个绝对的或相对的URL，将原封不动的作为重定向的位置。</span><br><span class="line">    默认返回一个临时的重定向；传递permanent=<span class="literal">True</span> 可以返回一个永久的重定向。</span><br><span class="line">    </span><br><span class="line">示例:</span><br><span class="line">    </span><br><span class="line">    你可以用多种方式使用redirect() 函数。</span><br><span class="line">    传递一个具体的ORM对象（了解即可）</span><br><span class="line">    将调用具体ORM对象的get_absolute_url() 方法来获取重定向的URL：</span><br></pre></td></tr></table></figure>

<p>2、返回一个orm对象</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">from django.shortcuts import redirect</span><br><span class="line"> </span><br><span class="line">def my_view(request):</span><br><span class="line">    ...</span><br><span class="line">    object = MyModel.objects.get(...)</span><br><span class="line">    return redirect(object)</span><br></pre></td></tr></table></figure>

<p>3、放回一个视图的名称</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">def my_view(request):</span><br><span class="line">    ...</span><br><span class="line">    return redirect(&apos;some-view-name&apos;, foo=&apos;bar&apos;)</span><br></pre></td></tr></table></figure>

<p>4、要重定向到的一个具体的网址</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">def my_view(request):</span><br><span class="line">    ...</span><br><span class="line">    return redirect(&apos;/some/url/&apos;)</span><br></pre></td></tr></table></figure>

<p>5、render和redict返回页面的区别</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">redict可以携带不同的数据，render携带的数据基本是一致的</span><br><span class="line">最简单的例子就是登陆后的调转页面</span><br></pre></td></tr></table></figure>

<p>6、关于301和302：　　　　　</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>）<span class="number">301</span>和<span class="number">302</span>的区别。</span><br><span class="line"></span><br><span class="line">　　<span class="number">301</span>和<span class="number">302</span>状态码都表示重定向，就是说浏览器在拿到服务器返回的这个状态码后会自动跳转到一个新的URL地址，这个地址可以从响应的Location首部中获取</span><br><span class="line">  （用户看到的效果就是他输入的地址A瞬间变成了另一个地址B）——这是它们的共同点。</span><br><span class="line"></span><br><span class="line">　　他们的不同在于。<span class="number">301</span>表示旧地址A的资源已经被永久地移除了（这个资源不可访问了），搜索引擎在抓取新内容的同时也将旧的网址交换为重定向之后的网址；</span><br><span class="line"></span><br><span class="line">　　<span class="number">302</span>表示旧地址A的资源还在（仍然可以访问），这个重定向只是临时地从旧地址A跳转到地址B，搜索引擎会抓取新的内容而保存旧的网址。 SEO302好于<span class="number">301</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="number">2</span>）重定向原因：</span><br><span class="line">（<span class="number">1</span>）网站调整（如改变网页目录结构）；</span><br><span class="line">（<span class="number">2</span>）网页被移到一个新地址；</span><br><span class="line">（<span class="number">3</span>）网页扩展名改变(如应用需要把.php改成.Html或.shtml)。</span><br><span class="line">        这种情况下，如果不做重定向，则用户收藏夹或搜索引擎数据库中旧地址只能让访问客户得到一个<span class="number">404</span>页面错误信息，访问流量白白丧失；再者某些注册了多个域名的</span><br><span class="line">    网站，也需要通过重定向让访问这些域名的用户自动跳转到主站点等。</span><br><span class="line"><span class="number">3</span>）临时重定向与永久重定向的理解</span><br><span class="line">	面向的是搜索引擎的机器人</span><br><span class="line">	A页面临时重定向到B页面，那搜索引擎收录的就是A页面</span><br><span class="line">	A页面永久重定向到B页面，那搜索引擎收录的就是B页面。</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://yoursite.com/2019/09/21/【Django】03视图函数 - 副本/" title="视图函数">http://yoursite.com/2019/09/21/【Django】03视图函数 - 副本/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/dxl/tags/Django/" rel="tag"># Django</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/dxl/2019/09/21/【Django】02路由系统/" rel="next" title="路由系统">
                <i class="fa fa-chevron-left"></i> 路由系统
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/dxl/2019/09/21/【Django】08cookie和session - 副本/" rel="prev" title="CooKies和Session">
                CooKies和Session <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/dxl/images/avatar.png" alt>
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/dxl/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/dxl/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/dxl/tags/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-sign-out"></i>
                我的友链
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="tencent://message/?Menu=yes&uin=1258517737&Site=QQ%E6%9E%81%E5%AE%A2&Service=300&sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45/" title="申请坑位" target="_blank">申请坑位</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一-Django的视图函数view"><span class="nav-number">1.</span> <span class="nav-text">一 Django的视图函数view</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1定义："><span class="nav-number">1.1.</span> <span class="nav-text">1.1定义：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-作用："><span class="nav-number">1.2.</span> <span class="nav-text">1.2 作用：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3那些可以作为响应的内容："><span class="nav-number">1.3.</span> <span class="nav-text">1.3那些可以作为响应的内容：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-4存放目录："><span class="nav-number">1.4.</span> <span class="nav-text">1.4存放目录：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5一个简单的视图"><span class="nav-number">1.5.</span> <span class="nav-text">1.5一个简单的视图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-6Django使用请求和响应对象来通过系统传递状态的过程："><span class="nav-number">1.6.</span> <span class="nav-text">1.6Django使用请求和响应对象来通过系统传递状态的过程：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二-CBV和FBV"><span class="nav-number">2.</span> <span class="nav-text">二 CBV和FBV</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1FBV（function-base-views）"><span class="nav-number">2.1.</span> <span class="nav-text">2.1FBV（function base views）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1CBV（class-base-views）"><span class="nav-number">2.2.</span> <span class="nav-text">2.1CBV（class base views）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3Djangourl的执行过程"><span class="nav-number">2.3.</span> <span class="nav-text">2.3Djangourl的执行过程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三-使用Mixin"><span class="nav-number">3.</span> <span class="nav-text">三 使用Mixin</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四-给视图加装饰器"><span class="nav-number">4.</span> <span class="nav-text">四 给视图加装饰器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1使用装饰器装饰FBV"><span class="nav-number">4.1.</span> <span class="nav-text">4.1使用装饰器装饰FBV</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2使用装饰器装饰CBV"><span class="nav-number">4.2.</span> <span class="nav-text">4.2使用装饰器装饰CBV</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3csrf-token的装饰器"><span class="nav-number">4.3.</span> <span class="nav-text">4.3csrf_token的装饰器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4重写dispatch方法"><span class="nav-number">4.4.</span> <span class="nav-text">4.4重写dispatch方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五-request对象"><span class="nav-number">5.</span> <span class="nav-text">五 request对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1请求相关的常用值"><span class="nav-number">5.1.</span> <span class="nav-text">5.1请求相关的常用值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2属性"><span class="nav-number">5.2.</span> <span class="nav-text">5.2属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-方法"><span class="nav-number">5.3.</span> <span class="nav-text">5.3 方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六-response对象"><span class="nav-number">6.</span> <span class="nav-text">六 response对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-1HttpResponse"><span class="nav-number">6.1.</span> <span class="nav-text">6.1HttpResponse</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-2JsonResponse对象"><span class="nav-number">6.2.</span> <span class="nav-text">6.2JsonResponse对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-3render"><span class="nav-number">6.3.</span> <span class="nav-text">6.3render</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-4redirect"><span class="nav-number">6.4.</span> <span class="nav-text">6.4redirect</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-hand-peace-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder"></span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/dxl/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/dxl/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/dxl/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/dxl/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/dxl/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/dxl/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '13B0JGDuA6ttduN8AQaR8CzF-gzGzoHsz',
        appKey: 'I13r9r5mVgq4jQYpYy6V4gW3',
        placeholder: '欢迎大佬指点~~~',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
